﻿$(document).ready(function () {
    enhancePager();
    enhanceDeleteButtons();
    getResult().show();
});

function enhancePager() {
    $(".pagerbutton").each(function () {
        var $button = $(this);
        $button.hide();

        var $form = $button.parents('form:first');

        var $a = $('<a href="' + $form.attr('action') + '/Page/' + $button.val() + '">' + $button.html() + '</a>');
        if ($button.attr('disabled')) {
            $a.addClass("pagerLinkDisabled");
        }
        else {
            $a.addClass("pagerLink");
        }
        $a.click(function (event) {
            event.preventDefault();
            $.ajax({
                url: $form.attr('action'),
                type: "POST",
                data: "PagerViewModel.CurrentPage=" + $button.val() + "&" + $form.serialize(),
                dataType: "html",
                success: function (data) {
                    var $result = getResult();
                    $result.html(data);
                    enhancePager();
                    enhanceDeleteButtons();
                }
            });
        });
        $button.after($a);
    });
}

function enhanceDeleteButtons() {
    $(".deleteButton").each(function () {
        var $button = $(this);
        $button.hide();

        var $form = $button.parents('form:first');

        var $a = $('<a href="' + $form.attr('action') + '/Delete/' + $button.val() + '">' + $button.html() + '</a>');
        if ($button.attr('disabled')) {
            $a.addClass("deleteLinkDisabled");
        }
        else {
            $a.addClass("deleteLink");
        }
        $a.click(function (event) {
            event.preventDefault();
            if (window.confirm('Are you sure you want to delete the product?')) {
                $.ajax({
                    url: $form.attr('action'),
                    type: "POST",
                    data: "Delete=" + $button.val() + "&" + $form.serialize(),
                    dataType: "html",
                    success: function (data) {
                        var $result = getResult();
                        $result.html(data);
                        enhancePager();
                        enhanceDeleteButtons();
                    }
                });
            }
        });
        $button.after($a);
    });
}